package com.kylin.module.specials.business;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.Config;
import com.kylin.common.util.FileOperater;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.specials.forms.SpecialForm;
import com.kylin.module.specials.orm.Special;
import com.kylin.module.study.business.StudyBlogic;

public class SpecialBlogic {

	private int pageSize = 5;

	protected static Logger log = Logger.getLogger(SpecialBlogic.class);

	public void addSpecial(SpecialForm form) throws BusinessException {
		log.debug("插入新的专题内容" + form.getTitle());
		Special obj = new Special();

		/*
		 * 如果该active状态为头条(ACTIVE_TOP), 将本专题的旧头条状态改为非 top ，其中
		 * 旧头条状态为（ACTIVE_HOT),改为ACTIVE_COMM 旧头条状态为（ACTIVE_HOT_TOP),改为ACTIVE_HOT.
		 */
		Short active = form.getActive();
		if (Special.ACTIVE_TOP.equals(active)
				|| Special.ACTIVE_HOT_TOP.equals(active)) {
			clearOldTop(form.getCatspecial());
		}
		
		obj.setActive(active);
		obj.setCreatedon(new Date());
		obj.setContent(form.getContent());
		if (form.getTitleimage() != null && form.getTitleimage().getFileSize() > 0) {
			log.debug("文件大小为:" + form.getTitleimage().getFileSize());
			String fileName = form.getTitleimage().getFileName();
			String imgUrl = null;
			try {
				imgUrl = FileOperater.saveUploadFile(Constants.IMG_SPECIAL,form.getTitleimage()
						.getInputStream(), fileName);
			} catch (IOException e) {
				log.error(e);
				e.printStackTrace();
				throw new BusinessException("上传文件图片失败",e);
			}
			obj.setTitleimage(imgUrl);
		}
		if(form.getAudourl()!=null && form.getAudourl().getFileSize() > 0){
			String audioPath = StudyBlogic.uploadMedia(Constants.MEDIA_SPECIAL, form.getAudourl(), null);
		    obj.setAudourl(audioPath);
		}
		obj.setLanguage(form.getLanguage());
		obj.setOrdering(form.getOrdering());
		obj.setTitle(form.getTitle());
		obj.setIntrotext(form.getIntrotext());
		obj.setCatspecial(new Dict(form.getCatspecial()));

		BaseHibernateDAO.save(obj);

	}

	/**
	 * 查找指定专题的头条
	 * 
	 * @param catid
	 * @return
	 * @throws BusinessException
	 */
	public List getTop(Long catid) throws BusinessException {
		Dict catsp = (Dict) BaseHibernateDAO.findById(Dict.class, catid);
		Short[] activeValues = new Short[] { Special.ACTIVE_TOP,
				Special.ACTIVE_HOT_TOP };
		PropertyCondition[] pConditions = new PropertyCondition[] {
		// 条件catspecial = new Dict(catid)
				new PropertyCondition("catspecial", catsp,
						PropertyCondition.OPERATOR_EQ),
				// 条件 active in (Special.ACTIVE_HOT,Special.ACTIVE_HOT_TOP)
				new PropertyCondition("active", activeValues,
						PropertyCondition.OPERATOR_IN) };
		return BaseHibernateDAO.findByPropertyConditions(Special.class,
				pConditions, null);
	}

	/**
	 * 批量设置专题文章为 热点文章
	 * 
	 * @param ids
	 *            一批专题文章的 id 集合
	 * @throws BusinessException
	 */
	public int toHot(String[] ids) throws BusinessException {
		String hsql = "update Special set active=" + Special.ACTIVE_HOT;
		for (int i = 0; i < ids.length; i++) {
			if (i == 0)
				hsql += " where ";
			else
				hsql += " or ";
			hsql += " id=" + ids[i];
		}
		return BaseHibernateDAO.execHql(hsql);
	}

	/**
	 * 修改一篇专题文章
	 * 
	 * @param form
	 * @throws BusinessException
	 */
	public void updateSpecial(SpecialForm form) throws BusinessException {
		log.debug("修改专题的标题为:" + form.getTitle());
		Special obj = (Special) BaseHibernateDAO.findById(Special.class, form
				.getId());
		obj.setTitle(form.getTitle());
		obj.setContent(form.getContent());
		obj.setCatspecial(new Dict(form.getCatspecial()));
		obj.setLastupdatedon(new Date());
		Short active = form.getActive();
		if (Special.ACTIVE_TOP.equals(active)
				|| Special.ACTIVE_HOT_TOP.equals(active)) {
			clearOldTop(form.getCatspecial());
		}
		obj.setActive(active);

		if (form.getTitleimage() != null
				&& form.getTitleimage().getFileSize() > 0
				&& form.getTitleimage().getFileName() != null
				&& !form.getTitleimage().getFileName().equals("")) {
			System.out.println(form.getTitleimage().getFileName() + " 文件尺寸："
					+ form.getTitleimage().getFileSize());
			String fileName = form.getTitleimage().getFileName();
			String imgUrl = null;
			try {
				imgUrl = FileOperater.updateUploadFile(Constants.IMG_SPECIAL,form.getTitleimage()
						.getInputStream(), fileName, obj.getTitleimage());
				obj.setTitleimage(imgUrl);
			} catch (IOException e) {
				log.error(e);
				e.printStackTrace();
				throw new BusinessException("上传文件图片失败",e);
			}
		}
		if(form.getAudourl()!=null || form.getAudourl().getFileSize() > 0){
			String audioPath = StudyBlogic.uploadMedia(Constants.MEDIA_SPECIAL, form.getAudourl(), obj.getAudourl());
		    obj.setAudourl(audioPath);
		}

		BaseHibernateDAO.update(obj);
	}

	public Special getSpecialById(Long id) throws BusinessException {
		return (Special) BaseHibernateDAO.findById(Special.class, id);
	}

	public void deleteSpecialById(Long id) throws BusinessException {
		Special special = getSpecialById(id);
		if (special != null) {
			BaseHibernateDAO.deleteById(Special.class, id);
		}
	}

	/**
	 * 清除旧的 头条专题文章 当保存或修改专题时，如果将当前保存的文章设为头条，就需要调用此方法清除旧的头条
	 * 
	 * @param catid
	 * @throws BusinessException
	 */
	private void clearOldTop(Long catid) throws BusinessException {
		List oldHot = getTop(catid);
		System.out.println("oldHot size=" + oldHot.size());
		for (int i = 0; i < oldHot.size(); i++) {
			Special oldObj = (Special) oldHot.get(i);
			System.out.println("oldObj=" + oldObj.getTitle());
			if (Special.ACTIVE_HOT_TOP.equals(oldObj.getActive()))
				oldObj.setActive(Special.ACTIVE_HOT);
			else
				oldObj.setActive(Special.ACTIVE_COMM);
			BaseHibernateDAO.update(oldObj);
		}
	}

	/**
	 * 根据分类id获得结果集
	 * 
	 * @param pageSize
	 * @param catid
	 * @throws BusinessException
	 */
	public DisplayPage searchByCat(int pageSize,Long catid) throws BusinessException {
		int pageNumber = 1;
		List conditions = new LinkedList();
		PropertyCondition cond = new PropertyCondition("catspecial",
					catid, PropertyCondition.OPERATOR_EQ);
		conditions.add(cond);
		CriteriaInfo cinfo = new CriteriaInfo(Special.class,conditions);
		DisplayPage page = PageManager.getDisplayPage(pageSize, pageNumber,cinfo);
		return page;
	}
	
	/**
	 * 按照指定的  专题分类 和 指定条数 查询专题记录
	 * @param cat
	 * @param num
	 * @return
	 * @throws BusinessException
	 */
	public List getListByCat(Dict cat,int num) throws BusinessException{
		List conditions = new LinkedList();
		PropertyCondition cond = new PropertyCondition("catspecial",cat, PropertyCondition.OPERATOR_EQ);
		conditions.add(cond);
		CriteriaInfo cinfo = new CriteriaInfo(Special.class,conditions);
		cinfo.setOrderby(Order.desc("ordering").desc("createdon"));
		DisplayPage page = PageManager.getDisplayPage(num, 1,cinfo);
		return page.getList();
	}
	
	public static String uploadMedia(String flag,FormFile formFile,String oldFile) throws BusinessException{
	    log.debug("flag="+flag+" ,formFile="+formFile+" ,oldFile="+oldFile);
			String filePath = null;
			if (formFile != null 
					&& formFile.getFileSize() > 0
					&& formFile.getFileName() != null
					&& !formFile.getFileName() .equals("")) {
	log.debug(" FileSize()="+formFile.getFileSize() + ", FileName()="+formFile.getFileName());			
				if(formFile.getFileSize() > Config.uploadMaxSize*1024)
					throw new BusinessException("上传文件尺寸最大不能超过 "+Config.uploadMaxSize+" KB");
				try{
					if(oldFile == null || oldFile.equals("")){
					    filePath = FileOperater.saveUploadFile(flag,formFile.getInputStream(), formFile.getFileName());
					}else{
						filePath = FileOperater.updateUploadFile(flag,formFile.getInputStream(), formFile.getFileName(),oldFile);
					}
				}catch(IOException e){
					throw new BusinessException("不能读取上传的文件："+e,e);
				}
			}
			return filePath;
		}
	public Dict getSpecialCatById(Long id) throws BusinessException{
		return (Dict)BaseHibernateDAO.findById(Dict.class, id);
	}
}
